package com.block.risk.service.type.item;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.block.risk.model.result.RiskJudgeResult;
import com.block.risk.service.IDefaultItemService;
import org.springframework.stereotype.Service;

@Service
public class YiShengItemService implements IDefaultItemService {
    @Override
    public RiskJudgeResult getControlResult(JSONObject resultDetial) {

        /**
         * 近一个月有放款记录 ，正常还款记录90+ 履约次数大于扣款失败笔数  贷款行为分600+ 贷款结清10
         */

        RiskJudgeResult riskJudgeResult = new RiskJudgeResult();
        riskJudgeResult.setPass(false);

        JSONObject currentReportDetail = resultDetial.getJSONObject("current_report_detail");
        JSONObject behaviorReportDetail = resultDetial.getJSONObject("behavior_report_detail");
        JSONObject applyReportDetail = resultDetial.getJSONObject("apply_report_detail");

        if (ObjectUtil.isEmpty(behaviorReportDetail)){
            riskJudgeResult.setResult("行为数据结果为空；【behavior_report_detail】");
            return riskJudgeResult;
        }

        //B22170007 近1个月货款总金额
        String loanAmount = behaviorReportDetail.getString("B22170007");
        if (StrUtil.equals(loanAmount, "0")){
            riskJudgeResult.setResult(StrUtil.format("一个月贷款金额不通过；【{}】", loanAmount));
            return riskJudgeResult;
        }

        //B22170001
        // 贷款行为分 600+
        String actionSource = behaviorReportDetail.getString("B22170001");
        if (Integer.valueOf(actionSource) < 600){
            riskJudgeResult.setResult(StrUtil.format("贷款行为分 600+以上不通过；【{}】", actionSource));
            return riskJudgeResult;
        }

        // 订单结清笔数8笔以上
        // 贷款已结清订单数
        String numberSettle = behaviorReportDetail.getString("B22170052");
        if (Integer.valueOf(numberSettle) < 10){
            riskJudgeResult.setResult(StrUtil.format("订单结清笔数10笔以上不通过；【{}】", numberSettle));
            return riskJudgeResult;
        }

        // 订单比例90以上
        // 正常还款订单数占贷款总订单数比例
        String numberRate = behaviorReportDetail.getString("B22170034");
        numberRate = numberRate.replace("%", "");
        if (Integer.valueOf(numberRate) < 90){
            riskJudgeResult.setResult(StrUtil.format("订单比例90以上不通过；【{}】", numberRate));
            return riskJudgeResult;
        }

        // 成功扣款笔数大于失败笔数.
        String numberSuccess = behaviorReportDetail.getString("B22170045");
        String numberFailed = behaviorReportDetail.getString("B22170035");
        if (Integer.valueOf(numberFailed) >= Integer.valueOf(numberSuccess)){
            riskJudgeResult.setResult(StrUtil.format("成功扣款笔数大于失败笔数不通过；成功扣款笔数【{}】失败笔数【{}】", numberSuccess, numberFailed ));
            return riskJudgeResult;
        }

        riskJudgeResult.setPass(true);
        riskJudgeResult.setResult("全景分控通过");
        return riskJudgeResult;
    }
}
